package com.zrkizzy.seckill.interceptor;

import com.zrkizzy.seckill.config.context.UserContext;
import com.zrkizzy.seckill.entity.User;
import com.zrkizzy.seckill.exception.NoLoginException;
import com.zrkizzy.seckill.service.core.IUserService;
import com.zrkizzy.seckill.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.zrkizzy.seckill.constant.CommonConst.USER_TICKET;

/**
 * 登录拦截器
 *
 * @author zhangrongkang
 * @since 2023/4/11
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = getLoginUser(request, response);
        // 放行
        if (null != user) {
            // 将用户对象存储到用户上下文中
            UserContext.setUserHolder(user);
            return true;
        }
        throw new NoLoginException();
    }

    /**
     * 获取当前登录用户
     *
     * @param request request请求
     * @param response response响应
     * @return 用户对象
     */
    private User getLoginUser(HttpServletRequest request, HttpServletResponse response) {
        // 获取当前请求中的用户
        String userTicket = CookieUtil.getCookieValue(request, USER_TICKET);
        // 判断签名是否存在
        if (StringUtils.hasLength(userTicket)) {
            return userService.getUserByCookie(userTicket, request, response);
        }
        return null;
    }
}
